package com.better.util;

import org.apache.commons.lang3.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/4.
 */
public class FiledAliasMapUtils {
    /**
     * JavaBean对象转化成FileAliasMap对象
     *
     * @param javaBean
     * @return
     * @author wfm
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static Map java2Map(Object javaBean,String excludeProperty) {
        Map map = new HashMap();
        try {
            // 获取javaBean属性
            BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if (propertyDescriptors != null && propertyDescriptors.length > 0) {
                String propertyName = null; // javaBean属性名
                Object propertyValue = null; // javaBean属性值
                for (PropertyDescriptor pd : propertyDescriptors) {
                    propertyName = pd.getName();
                    if (!propertyName.equals("class")) {
                        Method readMethod = pd.getReadMethod();
                        propertyValue = readMethod.invoke(javaBean, new Object[0]);
                        if (propertyValue != null&&!propertyValue.equals(propertyName)) {//值不为空则放入MAP
                            map.put(propertyName, "");
                        } else {
                            if(StringUtils.isNotEmpty(excludeProperty)&&!excludeProperty.equals(propertyName))
                            map.put(propertyName, propertyName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
